<?php
class Region {

	var $CI;
	var $region_model;

	public function __construct() {
		$this->CI =& get_instance();
		$this->CI->load->model("sys/sys_region_model");
		$this->region_model =$this->CI->sys_region_model;
	}

	public function get_regions($parent_id) {
		return $this->region_model->query_regions($parent_id);
	}
	
	public function  query_user_top_regions($user_id){
		return $this->region_model->query_user_top_regions($user_id);
	}
	public function get_parent_id($region_id){
		$region= $this->region_model->query_parent_id($region_id);
		if ($region) {
			return $region['parent_id'];
		}else{
			return -1;
		}
	}

	public function save_region($region){
		$check_result=$this->check_region($region);
		if (!$check_result['result']) {
			return $check_result;
		}
		$region_id =$this->region_model->insert_region($region);
		$result['result']=true;
		$result['redirect_url']=base_url()."index.php/sys_region_manage";
		return $result;
	}

	public function check_region($region,$region_id=""){
		$result['result'] =true;
		$result['message']="区域名称可以使用";
		if ($region['region_name']=="") {
			$result['result']=false;
			$result['message']="区域名称不能为空";
			return $result;
		}
		$region_info =$this->get_region_info_by_name($region['region_name']);
		if ($region_info=="") {
			$result['result']=true;
			$result['message']="区域名称可以使用";
			return $result;
		}
		if ($region['parent_id']==$region_info['parent_id']&&$region_info['region_id']!=$region_id) {
			$result['result']=false;
			$result['message']="相同区域已经存在,请重新输入";
			return $result;
		}
		return $result;
	}

	public function get_region_info($region_id){
		return $this->region_model->query_region_info($region_id);
	}

	public function get_region_info_by_name($region_name){
		return $this->region_model->query_region_info_by_name($region_name);
	}

	public function set_delete_region($region_id){
		$this->region_model->set_delete_region($region_id);

	}
	public function update_region($region,$region_id){
		$check_result=$this->check_region($region,$region_id);
		if (!$check_result['result']) {
			return $check_result;
		}
		$region_id =$this->region_model->update_region($region,$region_id);
		$result['result']=true;
		$result['redirect_url']=base_url()."index.php/sys_region_manage";
		return $result;
	}
}
?>